<template>
	<uni-popup ref='popup' :type="type">
		<textarea 
			focus
			v-model="replyTxt"
			maxlength="200" 
			confirm-type="确认" placeholder="评论或回复一下吧" />
		<button type="primary" :disabled="!replyTxt" @click="confirmReply">确 认</button>
	</uni-popup>
</template>

<script>
	export default {
		props: ['topicId', 'replies'],
		data (){
			return {
				type: 'bottom',
				replyTxt: '',
				replyId: ''
			}
		},
		mounted (){
			// #ifdef MP-WEIXIN
			this.type = 'top'
			// #endif
			
			// 监听，触发pop弹框
			this.$EventBus.$on('openPop', (res) => {
				this.$refs.popup.open()
				this.replyTxt = res.name ? ('@' + res.name + ' ') : ''
				this.replyId = res.id
			})
		},
		beforeDestroy (){
			// 销毁
			this.$EventBus.$off('openPop')
		},
		methods: {
			// 评论
			confirmReply (){
				const tmpTxt = this.replyTxt
				const data = {
					accesstoken: this.$store.state.access_token,
					content: tmpTxt
				}
				// @回复某人
				if(this.replyId){
					data['reply_id'] = this.replyId
				}
				this.replyTxt = ''
				this.$request.post('/topic/'+ this.topicId +'/replies', data)
					.then(result => {
						if(result.success){
							this.updateReply(result['reply_id'],  this.topicId, tmpTxt)
							this.$refs.popup.close()
						}else{
							this.replyTxt = tmpTxt
						}
						uni.showToast({
							title: result.success ? '评论成功' : '评论失败'
						})
					})
			},
			// 评论成功，往this.replies里添加数据，数据更新
			updateReply (reply_id, topic_id, content){
				const user_msg = this.$store.state.user_message
				const reply = {
					author: {
						loginname: user_msg['loginname'], 
						avatar_url: user_msg['avatar_url'],
					},
					content: `<div class="markdown-text">${content}</div>`,
					create_at: new Date().toGMTString(),
					id: reply_id,
					is_uped: false,
					reply_id: null,
					ups: []
				}
				this.$EventBus.$emit('add_reply', reply)
			}
		}
	}
</script>

<style lang="scss">
	button,
	uni-button{
		border-radius: 0;
		&::after{
			border-radius: 0;
		}
	}
</style>
